package cn.touna.jss.modules.custom.carmodel.synctask;

import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Created by Steve.Tao on 2017/11/21.
 */
public abstract class AbstractSyncModelService {

    /**
     * 同步用户
     */
    public final static String SYNC_USER = "SyncUser";

    /**
     * 同步车型<br/>
     * 当前一个任务执行在5~15分钟内，后期可以考虑将任务分解，减少异常对其他任务的影响<br/>
     * 对于互不干扰的任务，可以在分布式系统中完成
     *
     * @param taskNo
     * @return
     */
    abstract SyncModelResult refreshModel(String taskNo);

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    protected Date getDate(String str) {
        LocalDateTime localDateTime = LocalDateTime.from(dateTimeFormatter.parse(str));
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    protected BigDecimal getBigDeicimal(String str) {
        return BigDecimal.valueOf(Double.valueOf(str));
    }

    protected String getString(JSONObject obj, String field) {
        return getString(obj, field, "");
    }

    protected String getString(JSONObject obj, String field, String defaultValue) {
        String value = null;
        if (obj.containsKey(field))
            value = obj.getString(field);
        if (value == null)
            return defaultValue;
        return value;
    }

    protected String counterToMessage(Counter counter) {
        StringBuilder sb = new StringBuilder();
        sb.append(makeMsg(counter, "brand.insert", "插入品牌数"));
        sb.append(makeMsg(counter, "brand.update", "更新品牌数"));
        sb.append(makeMsg(counter, "brand.null", "品牌转换异常书"));

        sb.append(makeMsg(counter, "series.insert", "插入车系数"));
        sb.append(makeMsg(counter, "series.update", "更新车系数"));
        sb.append(makeMsg(counter, "series.null", "车系转换异常数"));
        sb.append(makeMsg(counter, "series.exception", "车系导入异常数"));

        sb.append(makeMsg(counter, "model.insert", "插入品牌数"));
        sb.append(makeMsg(counter, "model.update", "更新品牌数"));
        sb.append(makeMsg(counter, "model.null", "车型转换异常数"));
        sb.append(makeMsg(counter, "model.exception", "车型导入异常数"));
        return sb.toString();
    }

    private String makeMsg(Counter counter, String field, String title) {
        int count = counter.getCount(field);
        if (count == 0) {
            if (field.endsWith("null") || field.endsWith("exception") || field.endsWith("update"))
                return "";
        }
        return title + ": " + count + "，";
    }
}
